<?php
/**
* user.php
*
* Create on 2016-11-18
* Create by TT
*/
namespace haibao\cms\data\nh;

class User extends \haibao\cms\data\BaseMysql {
	public function __construct() {
		parent::__construct ( '\haibao\cms\model\data\nh\User' );
	}
	
	public function getStarWallList($query){
	    parent::__construct ( '\haibao\cms\model\data\nh\Photo' );
	    return $this->getAll($query);
	}
	
	/**
	 * 添加用户并给用户配发一张卡片
	 * @param \haibao\cms\model\data\nh\User $model
	 * @throws Exception
	 */
	public function addModel($model){
		
		$this->add($model);
			
		//给用户发明星卡片
		$this->addUserCard($model->Id, 1);

	}
	
	/**
	 * 通过微信openid设置头像
	 * @param string $openId
	 * @param string $url
	 */
	public function updateUserPhotoUrl($userId,$openId,$url){
		$this->query('update NH_User set PhotoUrl=%s where OpenId=%s', array($url,$openId));
			
		$this->addUserCard($userId, 1);
		
		$this->removeUserCacheByOpenId($openId);
	}
	
	public function closeUserById($openId){
		$this->query('update NH_User set Status=%s where OpenId=%s', array(\haibao\cms\model\data\nh\User::STATUS_TYPE_CLOSE,$openId));
		$this->removeUserCacheByOpenId($openId);
	}
	
	/**
	 * 通过微信openid得用户信息
	 * @param string $openId
	 * @return \haibao\cms\model\data\nh\User
	 */
	public function getUserByOpenId($openId){
		$userCache = new \haibao\cms\cache\Nh();
		$userModel = $userCache->getUserByOpenId($openId);
		if(empty($userModel)){
			$sql = 'select * from `NH_User` where OpenId = %s and Status = %s';
			$result = $this->query($sql,array($openId,\haibao\cms\model\data\nh\User::STATUS_TYPE_OPEN));
			while($result->fetch_assoc()){
				$userModel = new \haibao\cms\model\data\nh\User();
				$userModel->Id = $result->getData('Id');
				$userModel->Name = $result->getData('Name');
				$userModel->Mobile = $result->getData('Mobile');
				$userModel->OpenId = $result->getData('OpenId');
				$userModel->PhotoUrl = $result->getData('PhotoUrl');
				$userModel->IsWin = $result->getData('IsWin');
				$userModel->PhotoCard = $result->getData('PhotoCard');
				break;
			}
			if(!empty($userModel)){
				$userCache->setUser($userModel);
			}
		}
		
		return $userModel;
	}
	
	public function delUserCache($isSetPhotoCard = false){
		if($isSetPhotoCard){
			$sql = 'update `NH_User` set PhotoCard=50 where PhotoCard=0';
			$this->query($sql);
		}

		$userCache = new \haibao\cms\cache\Nh();
		$sql = 'select OpenId from `NH_User`';
		$result = $this->query($sql);
		while($result->fetch_assoc()){
			$userCache->removeUserByOpenId($result->getData('OpenId'));
		}
	}
	
	public function getSendPhotoSuccess($userId){
		$userCache = new \haibao\cms\cache\Nh();
		return $userCache->getSendPhotoSuccess($userId);
	}
	
	public function sendPhotoSuccess($userId){
		$userCache = new \haibao\cms\cache\Nh();
		return $userCache->setSendPhotoSuccess($userId);
	}
	
	/**
	 * 通过手机号得cms用户姓名
	 * @param string $mobile
	 * @return NULL
	 */
	public function getUserNameByMobile($mobile){
		$sql = 'select RealName from `User` where Mobile = %s and Status = 1';
		$result = $this->query($sql,array($mobile))->fetch_assoc();
		return $result['RealName'];
	}
	
	public function getUserByMobile($mobile){
		$sql = 'select * from `NH_User` where Mobile = %s';
		$result = $this->query($sql,array($mobile))->fetch_assoc();
		return $result;
	}
	
	/**
	 * 中奖用户
	 * @param array $userId
	 * @throws Exception
	 */
	public function setUserWin($userIds){
		self::beginTranscation ();
		try {
			$str = preg_replace('/(\d+)/', '%s', implode(',', $userIds));
			//删除卡池中此用户的所有卡片
			$this->query('delete from NH_Lottery where UserId in ('.$str.')', $userIds);
			
			//设置用户已中奖
			$this->query('update NH_User set IsWin=1 where Id in ('.$str.')', $userIds);
			
			// 将用户存入redis 用于推送消息
			$userCache = new \haibao\cms\cache\Nh();
			$userCache->setDrawUser(implode(',', $userIds));
		} catch ( \Exception $e ) {
			$this->rollback ();
			throw $e;
		}
		$this->endTranscation ();
		
		//清用户缓存
		$userInfo = array();
		$sql = 'select Id,OpenId,Name,PhotoUrl from `NH_User` where Id in ('.$str.')';
		$result = $this->query($sql,$userIds);
		while($result->fetch_assoc()){
			$this->removeUserCacheByOpenId($result->getData('OpenId'));
			$userInfo[$result->getData('Id')] = array('Name'=>$result->getData('Name'),'PhotoUrl'=>$result->getData('PhotoUrl'));
		}
			
		return $userInfo;
	}
	
	/**
	 * 给用户发卡片
	 * @param array $userIds	用户IDs
	 * @param int $sendCount	卡片数量
	 * @throws Exception
	 */
	public function sendCardToUser($userIds,$sendCount = 1,$isCache = false){
		$cardModels = array();
		foreach($userIds as $userId){
			$cardModels = $this->addUserCard($userId, $sendCount);
		}

		if($isCache){
			$userCache = new \haibao\cms\cache\Nh();
			$cacheUserIds = $userCache->getDrawCard();
			if($cacheUserIds){
				$cacheUserIds .= ','.implode(',', $userIds);
			} else {
				$cacheUserIds = implode(',', $userIds);
			}
			$userCache->setDrawCard($cacheUserIds);
		}
		return $cardModels;
	}
	
	/**
	 * 随机取明星卡片信息
	 * @param int $limit
	 * @return multitype:NULL
	 */
	public function getCardId($limit = 1){
		$cardModels = array();
		$sql = 'select Id,StarsId,TopicId,Name_CN,Name_EN from `NH_Card` where Status = 0 order by rand() limit %s';
		$result = $this->query($sql,array($limit));
		while($result->fetch_assoc()){
			$model = new \haibao\cms\model\data\nh\Card();
			$model->Id = $result->getData('Id');
			$model->StartId = $result->getData('StarsId');
			$model->TopicId = $result->getData('TopicId');
			$model->Name_CN = $result->getData('Name_CN');
			$model->Name_EN = $result->getData('Name_EN');
			$cardModels[$result->getData('Id')] = $model;
		}
		
		return $cardModels;
	}
	
	public function getCardCount(){
		$cardCount = 0;
		$sql = 'select count(*) as CardCount from `NH_Card` where Status = 0';
		$result = $this->query($sql)->fetch_assoc();
		if(!empty($result['CardCount'])){
			$cardCount = $result['CardCount'];
		}
		
		return $cardCount;
	}
	
	/**
	 * 用户微信上传图片
	 * @param haibao\cms\model\data\nh\Photo $model
	 * @param int $photoCard
	 * @throws Exception
	 */
	public function addPhotoModel($openId,$model,$photoCard = 0){
		$isSendCard = false;
		
		if($photoCard){
			$userModel = $this->getUserByOpenId($openId);
			if(!empty($userModel->PhotoCard) || $photoCard <= $userModel->PhotoCard){
		
				if($userModel->PhotoCard != 1){
					//设置用户已得过卡片
					$this->query('update NH_User set PhotoCard=%s where Id=%s', array($photoCard,$model->UserId));
		
					//清用户缓存
					$this->removeUserCacheByOpenId($openId);
				}
		
				$this->addUserCard($model->UserId,1);
		
				$isSendCard = true;
			}
		}
		
		$this->add($model);
		
		return $isSendCard;
		
	}
	
	public function getUserPhotoCount($userId){
		$num = 0;
		$param = array();
		$sql = 'select count(*) as Num from `NH_Photo` where Status=0';
		if($userId){
			$sql .= ' and UserId=%s';
			$param[] = $userId;
		}
		$result = $this->query($sql,$param)->fetch_assoc();
		if(!empty($result['Num'])){
			$num = $result['Num'];
		}
		return $num;
	}
	
	public function delUserPhoto($userId,$photoId){
		$this->query('update NH_Photo set Status=1 where UserId=%s and Id=%s', array($userId,$photoId));
	}
	
	public function sendUserCard($userId,$cardIds,$toUserId){
		$sendCardIds = array();
		$str = preg_replace('/(\d+)/', '%s', implode(',', $cardIds));
		$cardIds[] = $userId;
		$sql = 'select CardId from `NH_UserCard` where CardId in ('.$str.') and UserId=%s and Status=1';
		$result = $this->query($sql,$cardIds);
		while($result->fetch_assoc()){
				$sendCardIds[] = $result->getData('CardId');
		}
		if($sendCardIds){
			self::beginTranscation ();
			try {
				$userCardModels = array();
				foreach($sendCardIds as $id){
					$userCardModel = new \haibao\cms\model\data\nh\UserCard();
					$userCardModel->UserId = $toUserId;
					$userCardModel->CardId = $id;
					$userCardModel->Status = \haibao\cms\model\data\nh\UserCard::STATUS_TYPE_OPEN;
					$userCardModel->IsWin = 0;
					$userCardModels[] = $userCardModel;
				}
				$this->addAll($userCardModels);
				$str = preg_replace('/(\d+)/', '%s', implode(',', $sendCardIds));
				$sendCardIds[] = $userId;
				$this->query('delete from NH_UserCard where CardId in ('.$str.') and UserId=%s', $sendCardIds);
					
			} catch ( \Exception $e ) {
				$this->rollback ();
				throw $e;
			}
			$this->endTranscation ();
		}
	}
	
	/**
	 * 给用户发微信消息
	 * @param haibao\cms\model\data\nh\Message/array $model
	 */
	public function addMessage($model){

		//进Redis
		$userCache = new \haibao\cms\cache\Nh();
		if(is_array($model)){
			foreach($model as $m){
				$this->add($m);
				$userCache->setMessage(json_encode(array('Message'=>$m->Message,'MessageId'=>$m->Id)));
			}
		}else {
			$this->add($model);
			$userCache->setMessage(json_encode(array('Message'=>$model->Message,'MessageId'=>$model->Id)));
		}
	}
	
	public function getUserCardByUserId($userId){
		$cardIds = array();
		$sql = 'select CardId from `NH_Lottery` where UserId=%s';
		$result = $this->query($sql,array($userId));
		while($result->fetch_assoc()){
			$cardIds[] = $result->getData('CardId');
		}
		return $cardIds;
	}
	
	/**
	 * 用户选择卡片进入抽奖池
	 */
	public function addLotteryList($models){
		self::beginTranscation ();
		try {
			$this->addAll($models);
			
			foreach($models as $model){
				$this->query('update NH_UserCard set Status=0 where UserId=%s and CardId=%s', array($model->UserId,$model->CardId));
			}
		} catch ( \Exception $e ) {
			$this->rollback ();
			throw $e;
		}
		$this->endTranscation ();
	}

    public function getRandomPhotoList($limit = 1){
        $photo = '';
        $sql = "SELECT Id,PhotoUrl,Width,Height FROM `NH_Photo` where `Status` = 0 ORDER BY RAND() limit 0,%s;";
        $result = $this->query($sql,array($limit));
        while ($result->fetch_assoc()){
            $width = $result->getData('Width');
            $height = $result->getData('Height');
            if($width > 480 || $height > 672){
                if($width > $height){
                    $width = floor($width*672/$height);
                    $height = 672;
                }elseif($height >= $width){
                    $height = floor($height*480/$width);
                    $width = 480;
                }
            }
            $photo = array('Id'=>$result->getData('Id'),'PhotoUrl'=>\haibao\cms\business\control\Base::getImageLink($result->getData('PhotoUrl'),$width,$height,75));
        }
        return $photo;
    }

    /**
	 * 清空抽奖池
	 */
	public function delLottery($isSendCard = true){
		$this->query('delete from NH_Lottery');

		if($isSendCard){
			$this->sendCardToAllUser();
		}
	}

    public function sendCardToAllUser(){
		$userIds = array();
		$sql = 'SELECT Id from NH_User where `Status`=1 and IsWin=0';
		$result = $this->query($sql);
		while($result->fetch_assoc()){
			$userIds[] = $result->getData('Id');
		}

		if($userIds){
			$this->sendCardToUser($userIds);
		}
	}

    /**
	 * 得当前流程位置
	 * @return number
	 */
	public function getFlowType(){
		$userCache = new \haibao\cms\cache\Nh();
		$flowType = $userCache->getFlow();
		if(empty($flowType)){
			$sql = 'select Type from `NH_Flow`';
			$result = $this->query($sql)->fetch_assoc();
			if(!empty($result['Type'])){
				$flowType = (int)$result['Type'];
				$userCache->setFlow($flowType);
			}
		}

		return $flowType;
	}

    public function setFlowType($flowType){
		$this->query('update NH_Flow set Type=%s where Id=1', array($flowType));
		$userCache = new \haibao\cms\cache\Nh();
		$userCache->setFlow($flowType);
	}
    public function drawoffUserCard(){
		$sql = 'SELECT Id from NH_User where `Status`=1 and IsWin=0 and Id NOT IN (SELECT DISTINCT UserId from NH_Lottery)';
		$result = $this->query($sql);
		while($result->fetch_assoc()){
			$userId = $result->getData('Id');
			$sql = 'select CardId,UserId from `NH_UserCard` where UserId = %s and Status=1';
			$userCardData = $this->query($sql,array($userId));
			$lotteryModels = array();
			while($userCardData->fetch_assoc()){
				$lotteryModel = new \haibao\cms\model\data\nh\Lottery();
				$lotteryModel->UserId = $userCardData->getData('UserId');
				$lotteryModel->CardId = $userCardData->getData('CardId');
				$lotteryModels[] = $lotteryModel;
			}

			$this->addAll($lotteryModels);
			$this->query('update NH_UserCard set Status=0 where UserId = %s', array($userId));
		}
	}
    private function addUserCard($userId,$sendCount){
		$cardModels = $this->getCardId($sendCount);
		if($cardModels){
			$userCardModels = array();
			$cardIds = array();
			foreach($cardModels as $cardModel){
				$cardIds[] = $cardModel->Id;
				$userCardModel = new \haibao\cms\model\data\nh\UserCard();
				$userCardModel->UserId = $userId;
				$userCardModel->CardId = $cardModel->Id;
				$userCardModel->Status = \haibao\cms\model\data\nh\UserCard::STATUS_TYPE_OPEN;
				$userCardModel->IsWin = 0;
				$userCardModels[] = $userCardModel;
			}
			$this->addAll($userCardModels);
			//设置明星卡片已使用
			$str = preg_replace('/(\d+)/', '%s', implode(',', $cardIds));
			$this->query('update NH_Card set Status=1 where Id in ('.$str.')', $cardIds);
		}
		
		return $cardModels;
	}
	
	private function removeUserCacheByOpenId($openId){
		$userCache = new \haibao\cms\cache\Nh();
		$userCache->removeUserByOpenId($openId);
	}
}